<template>
  <div>
    <!-- 面包屑 -->
    <breadcrumb
      :breadcrumbArr="jsList.breadcrumbArr"
      :breadcrumbLastItem="breadcrumbLastItem"
      :state="state"
      @handleBack="handleBack"
    />
    <div v-if="isTrue" class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs
          v-model="activeName"
          class="el-tabs__customize"
          @tab-click="handleTabsClick"
        >
          <el-tab-pane label="基本信息" name="first">
            <baseInfo ref="baseInfo" :detail="detailInfo" />
          </el-tab-pane>

          <el-tab-pane label="财务信息" name="second">
            <financeInfo ref="financeInfo" :detail="detailInfo" isChange />
          </el-tab-pane>

          <el-tab-pane label="采购清单" name="third">
            <purchaseList ref="purchaseList" :detail="detailInfo" />
          </el-tab-pane>

          <el-tab-pane label="使用范围" name="fourth">
            <useRange ref="useRange" :detail="detailInfo" isChange />
          </el-tab-pane>

          <el-tab-pane label="付款方式" name="fifth">
            <paymentMode ref="paymentMode" :detail="detailInfo" isChange />
          </el-tab-pane>

          <el-tab-pane label="合同附件" name="sixth">
            <contractAppendix
              ref="contractAppendix"
              :uploadBusinessType="1"
              :state="state"
              v-model="uploadList"
            />
          </el-tab-pane>

          <el-tab-pane label="变更历史" name="seventh">
            <oneLineTable
              ref="histryChanges"
              :highlightNodeArr="['contractCode']"
              :tableTheadOptions="baseJsObj.histryChangeTableThead"
              :oneLineTableData="detailInfo.oldSmpPcConcList"
              @gotoDetail="gotoDetail"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle(0)"
            >保存并校验</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle(1)"
            >保存并提交</el-button
          >
        </li>
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回</el-button
          >
        </li>
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
import jsList from "../js";
import baseJsObj from "@/app/contractManagement/materialContract/contractDraft/js";
import { cloneDeep } from "lodash";
import baseInfo from "./baseInfo";
import purchaseList from "./purchaseList";
import contractComponent from "@/app/contractManagement/components";
import publicComponent from "@/basa/components/public";
import Mixin from "../mixins";
import {
  saveSmpContractCreation,
  editSmpContractCreation,
  getSmpPcConcChangeById,
  getSmpPcConcById
} from "../api";
import { mapActions, mapGetters } from "vuex";
import { proxyDateFormat } from "@/basa/utils";
export default {
  mixins: [Mixin],
  props: {
    state: {
      type: String,
      default: ""
    }
  },
  components: {
    baseInfo,
    financeInfo: contractComponent.financeInfo,
    purchaseList,
    useRange: contractComponent.useRange,
    paymentMode: contractComponent.paymentMode,
    contractAppendix: contractComponent.changeUploadInfo,
    breadcrumb: publicComponent.breadcrumb,
    oneLineTable: publicComponent.oneLineTable
  },
  data() {
    return {
      jsList,
      baseJsObj,
      breadcrumbLastItem: "合同变更",
      activeName: "first",
      isTrue: false,
      detailInfo: {},
      isFocus: "baseInfo",
      uploadList: [],
      tabsSelectArr: [],
      taxRateObj: {},
      afterVal: "",
      watchChangeList: {},
      lastFileSn: 0
    };
  },
  created() {
    this.init();
  },
  activated() {
    this.init();
  },
  deactivated() {
    this.nextIsTrue();
  },
  methods: {
    init() {
      this.getSmpPcConcInfo();
    },

    handleTabsClick({ label, name }) {
      if (this.tabsSelectArr.includes(name)) return;
      this.tabsSelectArr.push(name);
      this.detailInfo.tState = this.tState++;
    },

    // 保存 提交
    async submitHandle(operType) {
      try {
        // 基础合同
        let smpPcConcBO = await this.$refs.baseInfo.handleSubmit();
        // 财务信息
        let pcFinanceBOS = await this.$refs.financeInfo.handleSubmit();
        // 采购清单
        let smpConcMatLessListBOList =
          await this.$refs.purchaseList.handleSubmit();
        // 使用范围
        let smpUsableRangeBOList = await this.$refs.useRange.handleSubmit();
        // 付款方式
        let payTypeListBOS = await this.$refs.paymentMode.handleSubmit();

        if (pcFinanceBOS.length) {
          pcFinanceBOS.forEach(item => {
            item.materialSource = smpPcConcBO.materialSource;
            item.materialSourceCode = smpPcConcBO.materialSourceCode;
            item.contractPerson = smpPcConcBO.contractPerson;
            item.contractPersonTel = smpPcConcBO.contractPersonTel;
          });
        }

        let thirdCategoriesOfName = "";
        if (smpConcMatLessListBOList && smpConcMatLessListBOList.length) {
          thirdCategoriesOfName =
            smpConcMatLessListBOList[0].thirdCategoriesOfName;
          if (this.taxRateObj.dicValue !== "免税") {
            const newVal = this.taxRateObj.dicValue
              ? this.taxRateObj.dicValue.match(/\d+(.\d+)?/g)[0]
              : 0;
            this.afterVal = Number(newVal) / 100;
          } else {
            this.afterVal = this.taxRateObj.dicKey;
          }

          if (!this.getMultiRateCode) {
            smpConcMatLessListBOList = smpConcMatLessListBOList.map(n => ({
              ...n,
              taxRateCode: this.taxRateObj.dicKey,
              taxRatePercent: this.taxRateObj.dicValue,
              taxRate: this.afterVal
            }));
          }

          // 物资清单变更高亮
          smpConcMatLessListBOList.forEach((m, index, arr) => {
            const obj = this.watchChangeList.smpConcMatLessList[index];
            if (obj) {
              if (
                obj.taxRatePercent !== m.taxRatePercent ||
                obj.address !== m.address ||
                obj.currentUnitPriceIncludeTax !==
                  m.currentUnitPriceIncludeTax ||
                obj.currentChangeAmtExcludeTax !==
                  m.currentChangeAmtExcludeTax ||
                obj.currentNum !== m.currentNum ||
                obj.matDescribe !== m.matDescribe
              ) {
                this.$set(m, "isChangeFlag", 1);
              } else {
                this.$set(m, "isChangeFlag", 0);
              }
            } else {
              arr[index].isChangeFlag = 1;
            }
            this.$set(m, "sn", index);
          });
        }

        // 使用范围变更高亮
        let oldUseAbleList = this.watchChangeList.smpUsableRange;
        smpUsableRangeBOList.forEach((m, index) => {
          const item = oldUseAbleList[index];
          if (item) {
            this.$set(
              m,
              "isChangeFlag",
              item.applyOrgName != m.applyOrgName ? 1 : 0
            );
          }
          this.$set(m, "sn", index);
        });

        // 付款方式变更高亮
        if (this.state === "create") {
          let oldPayModeList = this.watchChangeList.payTypeListBOS;
          payTypeListBOS.forEach((m, index, arr) => {
            const item = oldPayModeList[index];
            // 先比较发票或结算
            // 判断old是否有当前可对比内容，否则为新增
            if (item) {
              if (m.smpPayTypeBO.payType !== item.smpPayTypeBO.payType) {
                arr[index].smpPayTypeBO.isChangeFlag = 1;
              } else {
                arr[index].smpPayTypeBO.isChangeFlag = 0;
              }
              // 再比较列表
              payTypeListBOS[index].smpPayTypeItemBOS.forEach((n, i, Arr) => {
                if (item.smpPayTypeItemBOS[i]) {
                  n.isRetentionMoney =
                    n.isRetentionMoney == null ? [] : n.isRetentionMoney;
                  item.smpPayTypeItemBOS[i].isRetentionMoney =
                    item.smpPayTypeItemBOS[i].isRetentionMoney == null
                      ? []
                      : item.smpPayTypeItemBOS[i].isRetentionMoney;

                  if (n.fixTimeCode === 0) {
                    if (
                      n.fixTimeCode !== item.smpPayTypeItemBOS[i].fixTimeCode ||
                      n.fixTimeLength !==
                        item.smpPayTypeItemBOS[i].fixTimeLength ||
                      n.fixTimeSonCode !==
                        item.smpPayTypeItemBOS[i].fixTimeSonCode ||
                      n.payTypeCode !== item.smpPayTypeItemBOS[i].payTypeCode ||
                      n.payRate !== item.smpPayTypeItemBOS[i].payRate ||
                      n.isRetentionMoney.toString() !==
                        item.smpPayTypeItemBOS[i].isRetentionMoney.toString()
                    ) {
                      Arr[i].isChangeFlag = 1;
                    } else {
                      Arr[i].isChangeFlag = 0;
                    }
                  } else if (n.fixTimeCode === 3) {
                    if (
                      n.fixTimeCode !== item.smpPayTypeItemBOS[i].fixTimeCode ||
                      n.datePicker !==
                        item.smpPayTypeItemBOS[i].fixTimeLength ||
                      n.payTypeCode !== item.smpPayTypeItemBOS[i].payTypeCode ||
                      n.payRate !== item.smpPayTypeItemBOS[i].payRate ||
                      n.isRetentionMoney.toString() !==
                        item.smpPayTypeItemBOS[i].isRetentionMoney.toString()
                    ) {
                      Arr[i].isChangeFlag = 1;
                    } else {
                      Arr[i].isChangeFlag = 0;
                    }
                  } else if (n.fixTimeCode === 5) {
                    if (
                      n.fixTimeCode !== item.smpPayTypeItemBOS[i].fixTimeCode ||
                      n.payTypeCode !== item.smpPayTypeItemBOS[i].payTypeCode ||
                      n.payRate !== item.smpPayTypeItemBOS[i].payRate ||
                      n.isRetentionMoney.toString() !==
                        item.smpPayTypeItemBOS[i].isRetentionMoney.toString()
                    ) {
                      Arr[i].isChangeFlag = 1;
                    } else {
                      Arr[i].isChangeFlag = 0;
                    }
                  } else {
                    // let retentionState = n.isRetentionMoney.length
                    //   ? n.isRetentionMoney[0]
                    //   : [];
                    if (
                      n.fixTimeCode !== item.smpPayTypeItemBOS[i].fixTimeCode ||
                      n.fixTimeLength !==
                        item.smpPayTypeItemBOS[i].fixTimeLength ||
                      n.payTypeCode !== item.smpPayTypeItemBOS[i].payTypeCode ||
                      n.payRate !== item.smpPayTypeItemBOS[i].payRate ||
                      n.isRetentionMoney.toString() !==
                        item.smpPayTypeItemBOS[i].isRetentionMoney.toString()
                    ) {
                      Arr[i].isChangeFlag = 1;
                    } else {
                      Arr[i].isChangeFlag = 0;
                    }
                  }
                }
              });
            }
          });
        } else {
          let oldPayModeList = this.watchChangeList.payTypeListBOS;
          payTypeListBOS.forEach((m, index, arr) => {
            const item = oldPayModeList[index];
            // 先比较发票或结算
            // 判断old是否有当前可对比内容，否则为新增
            if (item) {
              if (m.smpPayTypeBO.payType !== item.smpPayTypeBO.payType) {
                arr[index].smpPayTypeBO.isChangeFlag = 1;
              } else {
                arr[index].smpPayTypeBO.isChangeFlag = 0;
              }
              // 再比较列表
              payTypeListBOS[index].smpPayTypeItemBOS.forEach((n, i, Arr) => {
                if (item.smpPayTypeItemBOS[i]) {
                  n.isRetentionMoney =
                    n.isRetentionMoney == null ? [] : n.isRetentionMoney;
                  item.smpPayTypeItemBOS[i].isRetentionMoney =
                    item.smpPayTypeItemBOS[i].isRetentionMoney == null
                      ? []
                      : item.smpPayTypeItemBOS[i].isRetentionMoney;
                  if (n.fixTimeCode === 0) {
                    if (
                      n.fixTimeCode !== item.smpPayTypeItemBOS[i].fixTimeCode ||
                      n.fixTimeLength !==
                        item.smpPayTypeItemBOS[i].fixTimeLength ||
                      n.fixTimeSonCode !==
                        item.smpPayTypeItemBOS[i].fixTimeSonCode ||
                      n.payTypeCode !== item.smpPayTypeItemBOS[i].payTypeCode ||
                      n.payRate !== item.smpPayTypeItemBOS[i].payRate ||
                      n.isRetentionMoney.toString() !==
                        item.smpPayTypeItemBOS[i].isRetentionMoney.toString()
                    ) {
                      Arr[i].isChangeFlag = 1;
                    } else {
                      Arr[i].isChangeFlag = 0;
                    }
                  } else if (n.fixTimeCode === 3) {
                    if (
                      n.fixTimeCode !== item.smpPayTypeItemBOS[i].fixTimeCode ||
                      n.datePicker !==
                        item.smpPayTypeItemBOS[i].fixTimeLength ||
                      n.payTypeCode !== item.smpPayTypeItemBOS[i].payTypeCode ||
                      n.payRate !== item.smpPayTypeItemBOS[i].payRate ||
                      n.isRetentionMoney.toString() !==
                        item.smpPayTypeItemBOS[i].isRetentionMoney.toString()
                    ) {
                      Arr[i].isChangeFlag = 1;
                    } else {
                      Arr[i].isChangeFlag = 0;
                    }
                  } else if (n.fixTimeCode === 5) {
                    if (
                      n.fixTimeCode !== item.smpPayTypeItemBOS[i].fixTimeCode ||
                      n.payTypeCode !== item.smpPayTypeItemBOS[i].payTypeCode ||
                      n.payRate !== item.smpPayTypeItemBOS[i].payRate ||
                      n.isRetentionMoney.toString() !==
                        item.smpPayTypeItemBOS[i].isRetentionMoney.toString()
                    ) {
                      Arr[i].isChangeFlag = 1;
                    } else {
                      Arr[i].isChangeFlag = 0;
                    }
                  } else {
                    if (
                      n.fixTimeCode !== item.smpPayTypeItemBOS[i].fixTimeCode ||
                      n.fixTimeLength !==
                        item.smpPayTypeItemBOS[i].fixTimeLength ||
                      n.payTypeCode !== item.smpPayTypeItemBOS[i].payTypeCode ||
                      n.payRate !== item.smpPayTypeItemBOS[i].payRate ||
                      n.isRetentionMoney.toString() !==
                        item.smpPayTypeItemBOS[i].isRetentionMoney.toString()
                    ) {
                      Arr[i].isChangeFlag = 1;
                    } else {
                      Arr[i].isChangeFlag = 0;
                    }
                  }
                }
              });
            }
          });
        }

        if (smpPcConcBO) {
          smpPcConcBO = {
            ...smpPcConcBO,
            thirdCategoriesOfName
          };
        }

        // 附件上传
        const fileReqBOS = this.uploadList
          .filter(_ => _.businessSonType === "3" && _.addFlag)
          .map((n, i) => ({
            sn: this.lastFileSn + i + 1,
            createTime: n.createTime,
            fileDesc: n.fileDesc,
            fileInfoId: n.uploadId || n.fileInfoId
          }));

        if (payTypeListBOS.length) {
          payTypeListBOS = payTypeListBOS.map((n, i) => ({
            smpPayTypeBO: {
              ...n.smpPayTypeBO,
              sn: i,
              id: this.state === "create" ? null : n.smpPayTypeBO.id
            },
            smpPayTypeItemBOS: n.smpPayTypeItemBOS.map((m, i) => ({
              ...m,
              sn: i,
              id: this.state === "create" ? null : m.id
            }))
          }));
        }

        const data = {
          smpPcConcBO,
          pcFinanceBOS,
          smpConcMatLessListBOList,
          smpUsableRangeBOList,
          payTypeListBOS,
          fileReqBOS, // 合同附件
          operType
        };

        (this.state === "create"
          ? saveSmpContractCreation
          : editSmpContractCreation)(data).then(res => {
          const { code, message } = res.data;
          if (code === "0") {
            this.$message.success(message);
            this.handleBack();
          }
        });
      } catch (error) {
        this.activeName = error;
        if (["first", "second"].includes(error)) {
          this.$nextTick(() => {
            const errorFormEl = document.body.querySelector(".is-error");
            const errorText = errorFormEl.firstChild.innerText;
            const messageText = errorText.substring(
              0,
              errorText.lastIndexOf("：")
            );
            this.$showErrorMessage(`${messageText}未填写，请编辑后保存`);
            if (errorFormEl) {
              errorFormEl.scrollIntoView({
                behavior: "smooth", // 平滑过渡
                block: "start" // 上边框与视窗顶部平齐。默认值
              });
            }
          });
        }
      }
    },

    // 获取详情
    getSmpPcConcInfo() {
      const { id } = this.$route.params;
      let data = { concId: id, isShowWorkflow: 1 };
      if (this.state === "edit") data = { ...data, isChange: 1 };

      (this.state === "edit" ? getSmpPcConcById : getSmpPcConcChangeById)(data)
        .then(res => {
          const {
            data: { data }
          } = res;

          // this.$nextTick(() => {
          this.setTaxRateObj({
            dicKey: data.smpPcConc.taxRateCode,
            dicValue: data.smpPcConc.taxRatePercent
          });
          this.setCurrencyObj({
            code: data.smpPcConc.currencyCode,
            name: data.smpPcConc.currencyName
          });
          this.setOrgId(data.smpPcConc.reportInOrgId);
          this.setTaxRate(
            new this.$BigNumber(data.smpPcConc.taxRate).dividedBy(100)
          );
          this.setMultiRateCode(data.smpPcConc.multiRateCode === 0);
          this.setMultiRateStatus(false);
          this.setShowDoubleTable(!!data.smpPcConc.partyBId);
          this.setSupplierData({ supplierCode: data.smpPcConc.partyBId });
          this.setAgreementSelectStatus(!!data.smpPcConc.protocalCode);
          this.setIsOverseas(data.smpPcConc.isOverseas);
          // });

          // 处理变更历史
          if (data.oldSmpPcConcList.length) {
            data.oldSmpPcConcList = data.oldSmpPcConcList.map(n => ({
              ...n,
              compileDateStr: n.compileDate
                ? proxyDateFormat(n.compileDate)
                : ""
            }));
          }

          // 对照接口赋值
          const params = cloneDeep(
            this.state === "create" ? data : data.oldSmpPcConcRspBO
          );
          this.watchChangeList = {
            ...params,
            smpConcMatLessList: params.smpConcMatLessList.map(n => ({
              ...n,
              deliveryTime: n.deliveryTime
                ? proxyDateFormat(n.deliveryTime)
                : "",
              currentNum: n.currentNum !== null ? n.currentNum.toFixed(3) : "",
              currentUnitPriceExcludeTax:
                n.currentUnitPriceExcludeTax !== null
                  ? n.currentUnitPriceExcludeTax.toFixed(2)
                  : "",
              currentChangeAmtExcludeTax:
                n.currentChangeAmtExcludeTax !== null
                  ? n.currentChangeAmtExcludeTax.toFixed(2)
                  : "",
              currentUnitPriceIncludeTax:
                n.currentUnitPriceIncludeTax !== null
                  ? n.currentUnitPriceIncludeTax.toFixed(2)
                  : "",
              currentChangeAmtIncludeTax:
                n.currentChangeAmtIncludeTax !== null
                  ? n.currentChangeAmtIncludeTax.toFixed(2)
                  : "",
              rate: n.rate !== null ? n.rate.toFixed(2) : "",
              address:
                (n.deliveryAreaName || "") +
                (n.provinceName || "") +
                (n.cityName || "") +
                (n.countyName || "") +
                (n.deliveryPoints || "") // 交货地点
            }))
          };

          // 合并参数
          this.detailInfo = Object.assign(data, {
            state: this.state
          });

          // 过滤附件
          this.uploadList = data.concFiles;
          this.lastFileSn = data.concFiles.length
            ? data.concFiles.slice(-1)[0].sn
            : 0;

          if (this.state == "edit") {
            this.breadcrumbLastItem = data.smpPcConc.contractName;
          }
          this.isTrue = true;
        })
        .catch(e => {});
    },

    gotoDetail({ id }) {
      this.$router.push(`/contractManagement/contractChange/item-detail/${id}`);
    },

    ...mapActions([
      "setTaxRate",
      "setTaxRateObj",
      "setOrgId",
      "setMultiRateCode",
      "setMultiRateStatus",
      "setShowDoubleTable",
      "setSupplierData",
      "setAgreementSelectStatus",
      "setEchoProtocalData",
      "setIsOverseas",
      "setCurrencyObj"
    ])
  },
  computed: {
    ...mapGetters(["getTaxRateObj", "getMultiRateCode"])
  },
  watch: {
    getTaxRateObj(newVal) {
      this.taxRateObj = newVal;
    }
  }
};
</script>

<style lang="scss" scoped>
.el-tabs__customize {
  padding-bottom: 50px;
}
</style>
